import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHashHistory, createWebHistory ,createMemoryHistory} from 'vue-router';
import type { App } from 'vue';

import homeRouter from "./modules/home"
import csgoRouter from "./modules/csgo"
import shopRouter from "./modules/shop"
import promoteRouter from './modules/promote'
import caseboxRouter from './modules/casebox'
import userRouter from './modules/user'
import battleRouter from "./modules/battle";
import errorRouter from "./modules/error"
import staticRouter from "./modules/static"
import fairnessRouter from "@/router/modules/fairness";
import businessRouter from "@/router/modules/business";
import serviceRouter from "@/router/modules/service";
import rollRouter from "@/router/modules/roll";
import topRouter from "@/router/modules/top";
import welfateboxRouter from "@/router/modules/welfatebox";
import boxGame from "@/router/modules/boxGame";
import unpackRouter from "./modules/unpack"


const whiteList: Array<string> = ['/login', '/logout']

const routes: Array<RouteRecordRaw> = [
  homeRouter,
  csgoRouter,
  shopRouter,
  promoteRouter,
  caseboxRouter,
  userRouter,
  battleRouter,
  errorRouter,
  fairnessRouter,
  businessRouter,
  serviceRouter,
  rollRouter,
  topRouter,
  welfateboxRouter,
  boxGame,
  unpackRouter,
  ...staticRouter
]

// app router
const router = createRouter({
  history: createWebHashHistory(),
  routes: (routes as unknown) as RouteRecordRaw[],
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition
    } else {
      return {}
    }
  }
})

router.afterEach((to, from, failure) => {
  setTimeout(() => {
    var _hmt = _hmt || [];
    (function () {
      var key = import.meta.env.VITE_BAIDU_HM_KEY;
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?" + key;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  }, 0);
})

// reset router
export function resetRouter() {
  router.getRoutes().forEach((route) => {
    const { name } = route;
    if (name && !whiteList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

// config router
export function setupRouter(app: App<Element>) {
  app.use(router)
}

export default router
